#include "../../common/net.hpp"
#include "../../common/dispatcher.hpp"
#include "../../client/requestor.hpp"
#include "../../client/rpc_caller.hpp"
#include <thread>
#include <chrono>

void callback(const Json::Value& result)
{
    LOG(DEBUGLEVEL, "result: %d", result.asInt());
}

int main()
{
    MyRpc::BaseClient::ptr client = MyRpc::ClientFactory::create("127.0.0.1", 9090);
    client->setMessageCallBack(std::bind(&MyRpc::Dispatcher::OnMessage, MyRpc::disp.get(), std::placeholders::_1, std::placeholders::_2));
    auto requestor = std::make_shared<MyRpc::client::Requestor>();
    auto rpc_call = std::make_shared<MyRpc::client::RpcCaller>(requestor);

    // 把这回调函数注册给dispatcher模块
    auto cb = std::bind(&MyRpc::client::Requestor::onResponse, requestor.get(), std::placeholders::_1, std::placeholders::_2);
    MyRpc::disp->Register<MyRpc::BaseMessage>(MyRpc::MType::RSP_RPC, cb);

    // 先进行客户端连接服务端
    client->connect();
    // 获取连接的对象
    auto conn = client->connection();


    // 进行消息发送
    Json::Value params;
    params["num1"] = 11;
    params["num2"] = 22;

    // 同步发送请求
    Json::Value result;
    bool flag = rpc_call->call(conn, "Add", params, result);
    if(flag != false)
    {
        LOG(DEBUGLEVEL, "result: %d", result.asInt());
    }

    // 异步消息发送
    MyRpc::client::RpcCaller::AsyncResponse rsp;
    params["num1"] = 44;
    params["num2"] = 55;
    flag = rpc_call->call(conn, "Add", params, rsp);
    if(flag != false)
    {
        result = rsp.get();
        LOG(DEBUGLEVEL, "result: %d", result.asInt());
    }
    
    // 函数回调方法发送
    params["num1"] = 66;
    params["num2"] = 77;
    flag = rpc_call->call(conn, "Add", params, callback);

    // 等待5秒之后再关闭连接
    std::this_thread::sleep_for(std::chrono::seconds(5));
    // 关闭连接
    client->shutdown();
    return 0;
}
